import { createRouter, createWebHistory } from 'vue-router'
import DashboardView from '../views/dashboard/DashboardView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/LoginView.vue'),
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: DashboardView,
      meta: { requiresAuth: true }
    },
    {
      path: '/users',
      redirect: '/dashboard?view=users'
    },
    {
      path: '/roles',
      redirect: '/dashboard?view=roles'
    },
    {
      path: '/menus',
      redirect: '/dashboard?view=menus'
    },
    {
      path: '/posts',
      redirect: '/dashboard?view=posts'
    },
    {
      path: '/rankings',
      redirect: '/dashboard?view=rankings'
    },
    {
      path: '/tags',
      redirect: '/dashboard?view=tags'
    },
    // 添加通配符路由，处理所有未匹配的路径
    {
      path: '/:pathMatch(.*)*',
      redirect: to => {
        // 如果用户已登录，重定向到仪表盘
        const isLoggedIn = localStorage.getItem('isLoggedIn')
        return isLoggedIn ? '/dashboard' : '/login'
      }
    }
  ],
})

// 路由守卫，检查登录状态
router.beforeEach((to, from, next) => {
  // 检查localStorage中是否存在登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn')
  
  // 如果路由需要认证但用户未登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
  } 
  // 如果用户已登录但访问登录页
  else if (to.path === '/login' && isLoggedIn) {
    next('/dashboard')
  } 
  // 处理直接访问子路由的情况（如 /users, /roles, /menus, /posts）
  else if (to.path === '/users' && isLoggedIn) {
    next('/dashboard?view=users')
  }
  else if (to.path === '/roles' && isLoggedIn) {
    next('/dashboard?view=roles')
  }
  else if (to.path === '/menus' && isLoggedIn) {
    next('/dashboard?view=menus')
  }
  else if (to.path === '/posts' && isLoggedIn) {
    next('/dashboard?view=posts')
  }
  else if (to.path === '/rankings' && isLoggedIn) {
    next('/dashboard?view=rankings')
  }
  else if (to.path === '/tags' && isLoggedIn) {
    next('/dashboard?view=tags')
  }
  // 其他情况正常放行
  else {
    next()
  }
})

export default router
